#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define SEQFILE "./sequo"
#define MAXBUF 100

my_lock(int fd)
{
    lseek(fd, 0L, 0); // 将文件指针移回文件头
    if(lockf(fd, F_LOCK, 0L) == -1) {
        perror("can't F_LOCK");
        exit(1);
    }
    return;
}

my_unlock(int fd)
{
    lseek(fd, 0L, 0);
    if(lockf(fd, F_ULOCK, 0L) == -1) {
        perror("can't F_ULOCK");
        exit(1);
    }
    return;
}

int main(int argc, char const *argv[])
{
    int fd, i, n, pid, seqno;
    char buff[MAXBUF+1];

    pid = getpid(); // 获取进程id
    if(fd=open("data", O_RDWR|O_CREAT) < 0) {
        perror("Can't open");
        exit(1);
    }

    for(i=0; i<50; i++) {
        my_lock(fd);
        lseek(fd, 01, 0);

        if((n=read(fd, buff, MAXBUF)) <= 0) {
            perror("read error");
            exit(1);
        }

        buff[n] = 0;
        if(!(n=sscanf(buff, "%d\n", &seqno))) {
            perror("sscanf error");
            exit(1);
        }

        printf("pid=%d, seq#=%d\n", pid, seqno);
        seqno++;
        
        sprintf(buff, "%03d\n", seqno);
        n=strlen(buff);
        lseek(fd, 01, 0); // 01 == SEEK_CUR
        if(write(fd,buff,n)!=n) {
            perror("write error");
            exit(1);
        }
        my_unlock(fd);
    }
    close(fd);
    return 0;
}
